package com.zmn.oms.common.utils;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Objects;

/**
 * AES加解密实现
 *
 * @author xiewenbing
 * @date 2021/08/10
 */
@Slf4j
public class AesUtil {

    /**
     * 算法/模式/填充
     *
     **/
    private static final String CIPHER_MODE = "AES/ECB/PKCS5Padding";

    /**
     * 加解密方式
     */
    private static final String ENCRYPT_METHOD = "AES";

    /**
     * 秘钥随机算法
     */
    private static final String KEY_ALGORITHM = "SHA1PRNG";

    /**
     * 秘钥大小 - 128位
     */
    private static final int KEY_SIZE = 128;

    /**
     * AES加密-密钥
     * @param encryptKey
     * @param content
     * @return
     */
    private static String encode(byte[] encryptKey, String content) {

        try {
            Key key = new SecretKeySpec(encryptKey,ENCRYPT_METHOD);

            Cipher cipher = Cipher.getInstance(CIPHER_MODE);
            cipher.init(Cipher.ENCRYPT_MODE, key);

            byte[] encBytes = cipher.doFinal(content.getBytes("utf-8"));
            return Base64.getEncoder().encodeToString(encBytes);

        } catch (Exception e) {
            log.info("[AesUtil] encode occur exception - [{}] [{}] [{}]", parseByte2HexStr(encryptKey), content,e.getMessage());
        }

        return null;
    }

    /**
     * AES解密 - 密钥
     * @param encryptKey
     * @param content
     * @return
     */
    private static String decode(byte[] encryptKey, String content) {

        try {
            Key key = new SecretKeySpec(encryptKey,ENCRYPT_METHOD);

            Cipher cipher = Cipher.getInstance(CIPHER_MODE);
            cipher.init(Cipher.DECRYPT_MODE, key);

            byte[] decBytes = cipher.doFinal(Base64.getDecoder().decode(content));
            return new String(decBytes, "utf-8");

        } catch (Exception e) {
            log.info("[AesUtil] decode occur exception - [{}] [{}] [{}]", parseByte2HexStr(encryptKey), content,e.getMessage());
        }

        return null;
    }

    /**
     * 根据密码生成AES秘钥
     * @param password
     * @return
     */
    private static byte[] generateKey(String password) {

        try{
            KeyGenerator keyGenerator = KeyGenerator.getInstance(ENCRYPT_METHOD);
            SecureRandom secureRandom = SecureRandom.getInstance(KEY_ALGORITHM);
            secureRandom.setSeed(password.getBytes());
            keyGenerator.init(KEY_SIZE, secureRandom);
            SecretKey secretKey = keyGenerator.generateKey();

            return secretKey.getEncoded();
        } catch (Exception e) {
            log.info("[AesUtil] generate key product exception - [{}] [{}]", e.getMessage(),e.toString());
        }

        return null;
    }

    /**
     * AES加密
     * @param password
     * @param encryptContent
     * @return
     */
    public static String encrypt(String password, String encryptContent) {

        log.info("[AesUtil] encrypt,[{}] [{}]", password, encryptContent);

        if (Objects.isNull(password) || password.isEmpty() ||
                Objects.isNull(encryptContent) || encryptContent.isEmpty()) {
            log.info("[AesUtil] encrypt failed - param wrong");
            return null;
        }

        byte[] encryptKey = generateKey(password);
        if (Objects.isNull(encryptKey) || encryptKey.length <= 0) {
            log.info("[AesUtil] encrypt failed - generate key");
            return null;
        }

        String content = encode(encryptKey, encryptContent);

        log.info("[AesUtil] encrypt end ,[{}] [{}]", parseByte2HexStr(encryptKey), content);

        return content;
    }

    /**
     * AES解密
     * @param password
     * @param decryptContent
     * @return
     */
    public static String decrypt(String password, String decryptContent) {

        log.info("[AesUtil] decrypt,[{}] [{}]", password, decryptContent);

        if (Objects.isNull(password) || password.isEmpty() ||
                Objects.isNull(decryptContent) || decryptContent.isEmpty()) {
            log.info("[AesUtil] decrypt failed - param wrong");
            return null;
        }

        byte[] decryptKey = generateKey(password);
        if (Objects.isNull(decryptKey) || decryptKey.length <= 0) {
            log.info("[AesUtil] decrypt failed - generate key");
            return null;
        }

        String content = decode(decryptKey, decryptContent);

        log.info("[AesUtil] decrypt end ,[{}] [{}]", parseByte2HexStr(decryptKey), content);

        return content;
    }

    /**
     * 将二进制转换为十六进制字符串
     *
     * @param buf
     * @return 十六进制字符串
     */
    public static String parseByte2HexStr(byte[] buf) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将十六进制转换为二进制
     *
     * @param hexStr 十六进制数据
     * @return 二进制数组
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    public static void main(String[] args) {

    }
}
